package com.hw.one.transpot.util;

import java.util.LinkedList;
import java.util.List;

import com.hw.one.collect.entity.CommonData;
import com.hw.one.transpot.constant.TransportDataConstant;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/***
 * 数据采集传输工具类
 */
public class TransporterDataUtil {

	public void sendBytes(LinkedList<CommonData> msg) {
		this.connect(FILE_IP, FILE_PORT, msg);
	}

	EventLoopGroup group = null;

	public void connect(String ip, int port, LinkedList<CommonData> msg) {
		try {
			// 启动一个客户端程序
			group = new NioEventLoopGroup();
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
					.handler(new ChannelInitializer<Channel>() {
						@Override
						protected void initChannel(Channel ch) throws Exception {
							ch.pipeline().addLast("server-logging-handler", new LoggingHandler(LogLevel.DEBUG))
									.addLast("server-length-decoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4))
									.addLast("server-string-encoder", new StringEncoder())
									.addLast("server-length-encoder", new LengthFieldPrepender(4, false))
									.addLast("server-string-decoder", new StringDecoder());
							ch.pipeline().addLast(new TransporteDataHandler(msg));
						}
					});
			ChannelFuture f = b.connect(ip, port).sync();
			f.channel().closeFuture().sync();
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}

	public void shutdown() {
		if (null != group) {
			group.shutdownGracefully();
			group = null;
		}
	}

	public static void main(String[] args) throws InterruptedException {
	}

	public static final int FILE_PORT = TransportDataConstant.PORT;
	public static final String FILE_IP = TransportDataConstant.IP;
}
